<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input v-model="queryParmas.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="changValue" />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTreeRef"
          :data="treeData"
          :props="treeProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @node-click="handlerClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="excleExport">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table border stripe :data="userList">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template #default="{row}">
              <el-avatar v-if="row.staffPhoto" size="medium" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>

            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" align="center" />
          <el-table-column prop="mobile" label="手机号" align="center" />
          <el-table-column prop="workNumber" label="工号" align="center" />
          <el-table-column prop="formOfEmployment" label="聘用形式" align="center" :formatter="formatterFormOf" />
          <el-table-column prop="departmentName" label="部门" align="center" />
          <el-table-column prop="timeOfEntry" label="入职时间" align="center" />
          <el-table-column label="操作" align="center" width="140px">
            <template #default="{row}">
              <el-button type="text" @click="$router.push(`employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="assignRole(row.id)">角色</el-button>
              <div>
                <el-popconfirm
                  title="这是一段内容确定删除吗？"
                  @onConfirm="del(row.id)"
                >
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </div>

            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="queryParmas.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryParmas.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <ImportExcel :show-excel-dialog.sync="showExcelDialog" @update-list="loadList" />
    <AssignRole ref="assignRoleRef" :is-show-assign-role.sync="isShowAssignRole" />
  </div>
</template>

<script>
import ImportExcel from './components/import-excel.vue'
import { getDepartments } from '@/api/user'
import { delUser, getUserExcel, getUserList } from '@/api/employee'
import { listTree } from '@/utils'
import { formOfEm } from './constant/user'
import { saveAs } from 'file-saver'

import AssignRole from './components/assign-role.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel,
    AssignRole

  },

  data() {
    return {
      treeData: [],
      treeProps: {
        // 指定要展示的数据属性
        label: 'name',
        children: 'children'
      },
      // 查询列表的参数
      queryParmas: {
        page: 1,
        pagesize: 5,
        keyword: '',
        departmentId: '' // 部门 id

      },
      total: 0,
      userList: [],
      showExcelDialog: false,
      isShowAssignRole: false
    }
  },
  mounted() {
    this.loadList()
  },

  methods: {

    async loadList() {
      const res = await getDepartments()
      this.treeData = listTree(res, 0)

      this.queryParmas.departmentId = res[0].id

      this.$nextTick(() => {
        // 这里的回调什么时候执行呢？
        // 会在下一次 dom 更新完毕之后执行
        this.$refs.deptTreeRef.setCurrentKey(this.queryParmas.departmentId)
        this.loadUserList()
      })
    },
    async handlerClick(dept) {
      this.queryParmas.departmentId = dept.id
      // 部门变了 页码回调1
      this.queryParmas.page = 1
      await this.loadUserList()
    },
    // 获取用户信息列表
    async loadUserList() {
      const { rows, total } = await getUserList(this.queryParmas)
      this.userList = rows
      this.total = total
    },
    async handleSizeChange(pagesize) {
      this.queryParmas.pagesize = pagesize
      await this.loadUserList()
    },
    async handleCurrentChange(page) {
      this.queryParmas.page = page
      await this.loadUserList()
    },
    formatterFormOf(row) {
      const res = formOfEm.find(item => item.value === row.formOfEmployment)
      return res?.text ?? '未知'
    },
    // 根据名字模糊搜索
    changValue() {
      clearTimeout(this.time)
      this.time = setTimeout(() => {
        this.queryParmas.page = 1
        this.loadUserList()
      }, 500)
    },
    // 删除员工
    async del(id) {
      console.log(111)
      try {
        await delUser(id)
        this.$message.success('删除成功')
        await this.loadUserList()
      } catch (error) {
        console.log(error)
      }
    },
    // excel导出
    async excleExport() {
      const blob = await getUserExcel()
      saveAs(blob, '员工信息表.xlsx')
    },
    // 先获取数据再打开弹框
    async assignRole(id) {
      await this.$refs.assignRoleRef.getRoleList(id)
      this.isShowAssignRole = true
    }
  }

}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
      .el-table {
      margin-top: 10px;
    }
  }
}

</style>
